package szc.common.code.util;

import lombok.Cleanup;
import net.sf.sevenzipjbinding.IInArchive;
import net.sf.sevenzipjbinding.SevenZip;
import net.sf.sevenzipjbinding.impl.RandomAccessFileInStream;

import java.io.*;
import java.nio.charset.Charset;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

/**
 * @desc 文件解压工具类
 * @author songzc
 * @date 2022/6/20
 */
public class UnCompressionUtils {

    public static void main(String[] args) throws Exception {
        unZipFile("D:/temp/cloud-common-code.zip","D:/temp/666");
    }

    /**
     * 解压zip文件
     * @param zipPath
     * @param descDir
     */
    public static void unZipFile(String zipPath, String descDir) throws Exception {
        try {
            File zipFile = new File(zipPath);
            if (!zipFile.exists()) {
                throw new IOException("需解压文件不存在.");
            }
            File pathFile = new File(descDir);
            if (!pathFile.exists()) {
                pathFile.mkdirs();
            }
            ZipFile zip = new ZipFile(zipFile, Charset.forName("GBK"));
            int count = 0;
            for (Enumeration entries = zip.entries(); entries.hasMoreElements(); ) {
                ZipEntry entry = (ZipEntry) entries.nextElement();
                //避免文件名过长超出linux文件名长度限制255
                String zipEntryName;
                if(entry.getName().length() > 50){
                    //zipEntryName = entry.getName().substring(0,50) + count + entry.getName().substring(entry.getName().lastIndexOf("."));
                    zipEntryName = entry.getName();
                } else {
                    zipEntryName = entry.getName();
                }
                @Cleanup InputStream in = zip.getInputStream(entry);
                String outPath = (descDir + File.separator + zipEntryName).replaceAll("\\*", "/");
                // 判断路径是否存在,不存在则创建文件路径
                File file = new File(outPath.substring(0, outPath.lastIndexOf('/')));
                if (!file.exists()) {
                    file.mkdirs();
                }
                // 判断文件全路径是否为文件夹,如果是上面已经上传,不需要解压
                if (new File(outPath).isDirectory()) {
                    continue;
                }
                // 输出文件路径信息
                @Cleanup OutputStream out = new FileOutputStream(outPath);
                byte[] buf1 = new byte[1024];
                int len;
                while ((len = in.read(buf1)) > 0) {
                    out.write(buf1, 0, len);
                }
                in.close();
                out.close();
                count++;
            }
        } catch (Exception e) {
            throw new Exception("解压文件失败,"+e);
        }
    }

    public static void unRarFile(String rarPath, String targetFilePath) throws Exception {
        File outFile = new File(rarPath);
        // 目标目录不存在时，创建该文件夹
        if (!outFile.exists()) {
            outFile.mkdirs();
        }
        @Cleanup RandomAccessFile randomAccessFile = null;
        @Cleanup IInArchive inArchive = null;
        // 第一个参数是需要解压的压缩包路径，第二个参数参考JdkAPI文档的RandomAccessFile
        randomAccessFile = new RandomAccessFile(outFile.getPath(), "r");
        inArchive = SevenZip.openInArchive(null, new RandomAccessFileInStream(randomAccessFile));
        int[] in = new int[inArchive.getNumberOfItems()];
        for (int i = 0; i < in.length; i++) {
            in[i] = i;
        }
        // inArchive.extract(in, true, new ExtractZipFileCallback(inArchive, targetFilePath));
        inArchive.extract(in, false, new ExtractCallback(inArchive,targetFilePath));
    }

}
